package com.ljq.design.flyweight;

import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 享元模式的主要目的是实现对象的共享，即共享池，当系统中对象多的时候可以减少内存的开销，通常与工厂模式一起使用。
 * 像jdbc连接池
 * 
 *         CreateDate: 2017年12月1日
 */
public class ConnectionPool {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	private Vector<Connection> pool;  
     
	    /*公有属性*/  
	    private String url = "jdbc:mysql://localhost:3306/test";  
	    private String username = "root";  
	    private String password = "root";  
	    private String driverClassName = "com.mysql.jdbc.Driver";  
	  
	    private int poolSize = 10;  
	    private static ConnectionPool instance = null;  
	    Connection conn = null;  
	  
	    /*构造方法，做一些初始化工作*/  
	    private ConnectionPool() {  
	        pool = new Vector<Connection>(poolSize);  
	  
	        for (int i = 0; i < poolSize; i++) {  
//	                Class.forName(driverClassName);  
//	                conn = DriverManager.getConnection(url, username, password);  
	                conn = new Connection("pool-"+i);
	                pool.add(conn);  
	            
	        }  
	    }  
	    
	    public static ConnectionPool init() {
	    	if(null==instance) {
	    		instance = new ConnectionPool();
	    	}
	    	return instance;
	    }
	  
	    /* 返回连接到连接池 */  
	    public synchronized void release(Connection conn) {  
	        pool.add(conn);  
	    }  
	  
	    /* 返回连接池中的一个数据库连接 */  
	    public synchronized Connection getConnection() {  
	        if (pool.size() > 0) {  
	        	logger.info("getConnection start={}", pool);
	            Connection conn = pool.get(0);  
	            pool.remove(conn);  
	            logger.info("getConnection end={}", pool);
	            return conn;  
	        } else {  
	            throw new RuntimeException("连接池已用尽");
	        }  
	    }  
}
